#!/usr/bin/env python
from setup_utils import *
import os

# ids.server

actions, options, arg = getActions()
props = actions.getGlassfish("ids-setup.properties", ["glassfish", "libraries"])

prop_name = "ids.properties"
prop_list = ["icat.url", "plugin.main.class", "cache.dir", "preparedCacheSize1024bytes",
"preparedCount", "processQueueIntervalSeconds", "rootUserNames", "sizeCheckIntervalSeconds"]

if arg == "CONFIGURE":
    actions.configure(prop_name, prop_list)
    actions.setConfigured()

elif arg == "INSTALL":
    
    actions.checkConfigured()
    
    idsProperties = actions.getProperties(prop_name, prop_list)
    
    sprops = idsProperties.get("plugin.main.properties")
    if not sprops: print "You have specified plugin.main.class but not plugin.main.properties - which may be what you want"
    elif not actions.configFileExists(sprops):
        abort ("ids.properties defined plugin.main.properties to be " + sprops + " but the file has not been deployed. Have you installed the necessary ids plugins?")
  
    if not actions.configFileExists(idsProperties.get("cache.dir")):
        abort("Please create directory " + idsProperties.get("cache.dir") + " relative to the config directory as specified in ids.properties")
    
    if idsProperties.get("plugin.archive.class"):
        
        sprops = idsProperties.get("plugin.archive.properties")
        if not sprops: print "You have specified plugin.archive.class but not plugin.archive.properties - which may be what you want"
        elif not actions.configFileExists(sprops):
            abort ("ids.properties defined plugin.archive.properties to be " + sprops + " but the file has not been deployed. Have you installed the necessary ids plugins?")
               
        if not idsProperties.get("writeDelaySeconds"): abort("writeDelaySeconds is not set")
        if not idsProperties.get("datasetCacheSize1024bytes"): abort("datasetCacheSize1024bytes is not set")
        if not idsProperties.get("reader"): abort("reader is not set")
       

    actions.installFile("ids.properties")
   
    try:          
        app = actions.getAppName("ids.server")
        if app: actions.asadmin("undeploy " + app)
                        
        actions.deploy("ids.server-*.war", deploymentorder=120, libraries=props["libraries"].split())
                      
    except Exception, e:
        raise
        abort(str(e))
                
else:  # UNINSTALL
    
    actions.removeFile("ids.properties") 
    actions.removeFile("ids-storage.properties")
    
    try:
        app = actions.getAppName("ids.server")
        if app: actions.asadmin("undeploy " + app)
                  
    except Exception, e:
        abort(str(e))       
    
            
    
